package com.example.forum.controller;

import com.example.forum.service.DiscussPostService;
import com.example.forum.utils.SimpleUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/test")
public class TestController {
    @Autowired
    private DiscussPostService discussPostService;

    @RequestMapping("findAll")
    @ResponseBody
    public String findAll(@RequestParam(value = "userId",required = false,defaultValue = "0") String userId,
                          @RequestParam(value = "start",required = false,defaultValue = "0") int start){
        return discussPostService.findAll(userId,start,10).toString();
    }

    @RequestMapping("/cookie/setCookie")
    @ResponseBody
    public String cookieTest(HttpServletResponse response){
        Cookie cookie=new Cookie("code","123");
        cookie.setPath("/test/cookie");
        cookie.setMaxAge(60*10);
        response.addCookie(cookie);
        return "set cookie";
    }

    @RequestMapping("/cookie/getCookie")
    @ResponseBody
    public String cookieTest1(@CookieValue("code") String code){
        System.out.println(code);
        return "get cookie";
    }

    @RequestMapping("/session/setSession")
    @ResponseBody
    public String setSession(HttpSession session){
        session.setAttribute("str","yao");
        return "set session";
    }

    @RequestMapping("/session/getSession")
    @ResponseBody
    public String getSession(HttpSession session){
        Object str = session.getAttribute("str");
        System.out.println(str);
        return "get session";
    }

    @RequestMapping("/testAjax")
    @ResponseBody
    public String testAjax(){
        int code=0;
        String msg="发送异步请求";
        String json = SimpleUtils.toJson(code, msg);
        return json;
    }
}
